<?php
namespace Common\Model;

class OrderModel extends CommonModel{
	
	protected $_validate = array(
			array('contact_name','require','请输入联系人姓名'),
			array('contact_phone','require','请输入联系电话'),
			array('contact_phone','/^(1\d{10})|((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/','联系电话格式有误'),
			array('contact_province','require','请选择省份'),
			array('contact_city','require','请选择城市'),
			array('contact_district','require','请选择地区'),
			array('contact_address','require','请填写详细地址'),
			
			array('logistic_company','require','请输入物流公司名称'),
			array('logistic_number','require','请输入物流单号'),
	);
	protected $_link = array(
			'goods'=>array(
					'mapping_type'      => self::BELONGS_TO,
					'class_name'        => 'Goods',
					'foreign_key'        => 'goods_id',
			),
			'perinfo'=>array(
					'mapping_type'      => self::HAS_ONE,
					'class_name'        => 'Repayment',
					'foreign_key'        => 'order_id',
			),
	);
	public function create_order($info){
		$this->error = '系统繁忙，操作失败！';
		//真实性
		$goods_info = D('Goods')->where(array('id'=>$info['goods_id'],'status'=>'1','delete_status'=>'1'))->find();
		if(empty($goods_info)){
			$this->error = '商品不存在或已下架';
			return false;
		}
		//库存
		if($goods_info['type'] == '1'){
			$spec_info = D('GoodsSpec')->where(array('id'=>$info['spec_id']))->find();
			if($info['order_num'] > $spec_info['store']){
				$this->error = '抱歉，该商品库存不足';
				return false;
			}
		}else{
			if($info['order_num'] > $goods_info['store']){
				$this->error = '抱歉，该商品库存不足';
				return false;
			}
		}
		//地址
		$address_info = D('Address')->where(array('id'=>$info['address_id']))->find();
		if(empty($address_info)){
			$this->error = '请设置收获信息';
			return false;
		}
		$order = array();
		$order['user_id'] = $info['user_id'];
		$order['order_type'] = $info['order_type'];
		$order['order_sn'] = get_order_sn();
		$order['order_num'] = $info['order_num'];
		$order['order_price'] = $info['order_price'];
		$order['goods_id'] = $goods_info['id'];
		$order['goods_name'] = $goods_info['goods_name'];
		$order['goods_pic'] = $goods_info['goods_logo'];
		$order['goods_price'] = $goods_info['price'];
		$order['goods_profile'] = $goods_info['profile'];
		$order['goods_spec'] = $spec_info['color'];
		$order['address_id'] = $address_info['id'];
		$order['contact_user'] = $address_info['name'];
		$order['contact_phone'] = $address_info['phone'];
		$order['contact_area'] = $address_info['area'];
		$order['contact_address'] = $address_info['address'];
		$order['service'] = $info['service'];
		$order['vip_note'] = $info['vip_note'] ? $info['vip_note'] : '';
		$order['deposit'] = $info['deposit'] ? $info['deposit'] : 0 ;
		$order_id = $this->add($order);
		if($order_id){
			//减库存
			($goods_info['type'] == '1') && D('GoodsSpec')->where(array('id'=>$spec_info['id']))->setDec('store',$info['order_num']);
			D('Goods')->where(array('id'=>$goods_info['id']))->setDec('store',$info['order_num']);
			return $this->find($order_id);
		}else{
			return false;
		}
		
	}
}